package main

import (
	"code.google.com/p/marius/simplenote/db"
	"flag"
	"log"
	"os"
	"time"
)

var dbPath *string = flag.String("f", os.Getenv("HOME")+"/.notedb", "Path to database")

func mods(path string) <-chan time.Time {
	ch := make(chan time.Time)

	go func() {
		lastMod := time.Unix(0, 0)
		for {
			info, err := os.Stat(path)
			if err != nil {
				time.Sleep(5 * time.Second)
				continue
			}

			if info.ModTime().After(lastMod) {
				lastMod = info.ModTime()
				ch <- lastMod
			}

			time.Sleep(3 * time.Second)
		}
	}()

	return ch
}

func syncForever(interval time.Duration) {
	mods := mods(*dbPath)
	lastSync := time.Unix(0, 0)

	for {
		select {
		case t := <-mods:
			if !t.After(lastSync) {
				continue
			}
			log.Printf("file was modified at %s", t)

		case <-time.After(120 * time.Second):
			log.Printf("timer")
		}

		db, err := db.Open(*dbPath)
		start := time.Now()
		if err != nil {
			log.Printf("error opening db: %s", err)
			continue
		}

		syncTime, err := db.Sync()
		if err != nil {
			log.Printf("error syncing: %s", err)
			continue
		}

		lastSync = *syncTime

		log.Printf("synced in %s", time.Since(start))
	}
}

func main() {
	flag.Parse()

	// Pretty boring. That's it, all we do is sync forever.
	syncForever(30 * time.Second)
}
